/**
 * Project: apollo-base-mvc
 * 
 * File Created at 2016年5月18日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;

/** 
* @ClassName: FileUploadProgressListener 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2016年5月18日 上午8:50:47 
* @version V1.0 
*/
public class FileUploadProgressListener implements ProgressListener {

	public final static String DEFAULT_FILE_UPLOAD_PROGRESS_SESSION_KEY = "upload_session_key";

    private HttpSession session;

    public FileUploadProgressListener(HttpServletRequest request) {
        session = request.getSession();

        FileUploadProgress progress = new FileUploadProgress();
        session.setAttribute(DEFAULT_FILE_UPLOAD_PROGRESS_SESSION_KEY, progress);
    }

    private long megaBytes = -1;

    @Override
    public void update(final long pBytesRead, final long pContentLength, final int pItems) {
        long mBytes = pBytesRead / 1000000;
        if (megaBytes == mBytes) {
            return;
        }
        megaBytes = mBytes;
        System.out.println("We are currently reading item " + pItems);
        if (pContentLength == -1) {
            System.out.println("So far, " + pBytesRead + " bytes have been read.");
        } else {
            System.out.println("So far, " + pBytesRead + " of " + pContentLength
                    + " bytes have been read.");
        }

        FileUploadProgress status = (FileUploadProgress) session.getAttribute(DEFAULT_FILE_UPLOAD_PROGRESS_SESSION_KEY);
        status.setBytesRead(pBytesRead);
        status.setContentLength(pContentLength);
        status.setItems(pItems);
    }
}
